<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\Store;
use App\Services\Common;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Log;
use Ixudra\Curl\Facades\Curl;
use DB;

class StoreController extends Controller
{
	use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('店铺管理')
            ->description('店铺信息')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('店铺信息')
            ->description('详情')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('商家信息编辑')
            ->description('')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('商家添加')
            ->description('新增')
            ->body($this->form());
    }

//  public function update(Request $request, $id)
//  {
//
//  }

//  /**
//   * Handle update.
//   *
//   * @param int $id
//   *
//   * @return \Symfony\Component\HttpFoundation\Response
//   */
//  public function update($id, $data = null)
//  {
//
//      return $this->returnMsg(1, $id);
//  }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Store);

        $grid->sId('ID');
        $grid->sName('店名');
        $grid->sManager('店长');
        $grid->sPhone('电话');
        $grid->sFixedAssets('固定资产价值');
        $grid->sBorrowAssets('借用资产价值');
        $grid->sLeaseAssets('每月固定支出');
        $grid->sTotalCashFlow('总收入');
        $grid->sTotalProfit('总利润');
        $grid->sClerkNum('职员数量');
        $grid->sMemberNum('会员数量');

		// 不存的字段列
		$grid->sAvgConsumption('人均消费')->display(function () {
			if ($this->sMemberNum == 0){
				return 0;
			}else{
				return number_format($this->sTotalCashFlow/$this->sMemberNum, 2);
			}
		});

        $grid->sOpenDate('开店日期');

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});

		$grid->actions(function ($actions) {
		    $actions->disableDelete();
//		    $actions->disableEdit();
//		    $actions->disableView();
		});

		$sId = Admin::user()->sId;
// \print_r('fffffffffffff');exit;
		if ($sId === 0){
			$grid->filter(function($filter){

			    // 去掉默认的id过滤器
			    $filter->disableIdFilter();

			    $filter->column(1/2, function ($filter) {
			    	$filter->equal("sProvinceCode", "省")->select($this->getAreaSelectData())->load('sCityCode', 'store/getAreaSelectData', 'areaCode', 'areaName');
			    	$filter->equal("sCityCode", "市")->select()->load('sDistrictCode', 'store/getAreaSelectData', 'areaCode', 'areaName');
			    	$filter->equal("sDistrictCode", "区")->select($this->getAreaSelectData());
				});

				$filter->column(1/2, function ($filter) {
					$filter->like('sName', '店名');
				    $filter->like('sManager', '店长');
				    $filter->like('sPhone', '手机号');
				});

			});
		}

		$sId = Admin::user()->sId;
		if ($sId != 0){
			$grid->disableCreateButton();
		}

		// 默认展开筛选框
		$grid->expandFilter();

		// 禁用行选择checkbox
		$grid->disableRowSelector();

		// 禁用导出
		$grid->disableExport();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
    	$Store = new Store();
        $show = new Show($Store->findOrFail($id));

        $show->sId('ID');
        $show->sName('店名');
        $show->sManager('店长');
        $show->sPhone('手机号');
        $show->sLogo('logo')->image();
        $show->sDesc('店铺描述');
        $show->sOpenDate('开业日期');
        $show->sMemo('备注');
        $show->createUser('创建人');
        $show->createTime('创建时间');
        $show->updateUser('最后修改人');
        $show->updateTime('最后修改时间');

		$show->panel()->tools(function ($tools) {
//	        $tools->disableEdit();
//	        $tools->disableList();
	        $tools->disableDelete();
	    });

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
    	// 隐藏图片删除按钮
        $script = <<<EOT

setTimeout("$('.glyphicon-trash').parent().hide()", 100 )

EOT;
		Admin::script($script);

        return Admin::Form(Store::class, function (Form $form) {

			$form->hidden('sId');
			$form->text('sName', '店铺名称')->rules("required", ['required' => '请填写店铺名称']);
			$form->text('sManager', '店长姓名')->rules("required", ['required' => '请填写店长姓名']);
			$form->mobile('sPhone', '店长电话')->rules('required|regex:/^[1][0-9]{10}$/', [
        									'required' => '请填写手机号',
        									'regex' => '手机号格式不正确'
        									])
        									->attribute(['style' => 'width: 25%'])
                                            ->help('该电话将作为店铺登录账号');
        	// $defaultImg = 'http://images.common.think1st.cn/ami_logo.jpg';
        	$form->image('sLogo', 'logo图片')->uniqueName();
        	$form->textarea('sDesc', '店铺描述');
        	$form->distpicker(['sProvinceCode', 'sCityCode', 'sDistrictCode'])->attribute('data-value-type', 'code')->rules("required", ['required' => '请选择店铺所在地']);;
        	$form->text('sAddress', '店铺地址');
        	$form->latlong('sLongitude', 'sLatitude', '经纬度')->height(500);
        	$form->date('sOpenDate', '开业日期')->format('YYYY-MM-DD')->attribute(['style' => 'width: 25%']);
        	$form->textarea('sMemo', '备注');

            // 忽略掉不需要保存的字段 这句在api提交数据方式中无效
            $form->ignore(['scId', 'sFixedAssets', 'sTotalCashFlow', 'sTotalProfit', 'sClerkNum', 'sMemberNum', 'sAvgConsumption', 'createUser', 'createTime', 'updateUser', 'updateTime']);

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});

            $form->saving(function ($form) {

                $sinfo = DB::table('store')
                            ->where('sName', $form->sName)
                            ->first();
                if (!empty($sinfo)){
                    $error = new MessageBag([
                        'title'   => '保存失败！',
                        'message' => '该店名已存在，请修改！',
                    ]);

                    return back()->withInput()->with(compact('error'));
                }
            });

			$form->saved(function ($form) {

                $sinfo = DB::table('store')
                            ->where('sName', $form->sName)
                            ->where('sPhone',  $form->sPhone)
                            ->first();
                $sLogo = $sinfo->sLogo;
                if (\substr($sLogo, 0, 4) != 'http'){
                    $sLogo = 'http://images.common.think1st.cn/'.$sLogo;
                    DB::table('store')->where('sId', $sinfo->sId)->update(['sLogo'=>$sLogo]);
                }
			});

       });
    }

    // 获取区域列表下拉框数据
    public function getAreaSelectData($parentCode=''){

		if (isset($_GET['q'])){
			$parentCode = $_GET['q'];
		}
    	$Common = new Common();
    	$baseData = $Common->getAreaList($parentCode);

    	if (isset($_GET['q'])){
    		return $baseData;
    	}
    	$selectData = array();
    	foreach($baseData as $info){
    		$selectData[$info['areaCode']] = $info['areaName'];
    	}

    	return $selectData;
    }
    // 登录用户多店数据
        public function setMoreStoreLogin(Request $request){
    		$admin_code=!empty($request->admin_code) ? trim($request->admin_code):'';
    		if($admin_code!=""){
    			$Common = new Common();
    			$Common->setMoreStoreLogin($request);
    		}
        	header("Location: /admin");
        }
}
